<template>
  <div class="matchSubmit">
    <div class="submit-add" v-if="userRole == 1 && signupStatus == 0">
      <!-- <van-uploader :after-read="afterRead" :max-count="1" accept="image/*"> v-if="wxReadyOk"-->
      <van-button icon="plus" type="info" @click="chooseshow = true" v-if="wxReadyOk">作品上传</van-button>
      <!-- </van-uploader> -->
    </div>
    <div class="list-content">
      <div class="list-group">
        <div class="list-box" v-for="item in rightList" :key="item.id">
          <div class="list-item">
            <img :src="imgBasePath + item.path" alt="" @click="imagePreview(item)" v-if="item.source_type == 1">
            <img :src=" `${publicPath}source/img/video.jpg`" alt="" @click="imagePreview(item)" v-if="item.source_type == 2">
            <div class="title">{{ item.path_name }}</div>
            <div class="del" v-if="userRole == 1 && signupStatus == 0 && activeStatus == 1"><van-button block
                type="danger" @click="worksDel(item.id)">删除</van-button></div>
          </div>
        </div>
      </div>
      <div class="list-group">
        <div class="list-box" v-for="item in leftList" :key="item.id">
          <div class="list-item">
            <img :src="imgBasePath + item.path" alt="" @click="imagePreview(item)" v-if="item.source_type == 1">
            <img :src=" `${publicPath}source/img/video.jpg`" alt="" @click="imagePreview(item)" v-if="item.source_type == 2">
            <div class="title">{{ item.path_name }}</div>
            <div class="del" v-if="userRole == 1 && signupStatus == 0 && activeStatus == 1"><van-button block
                type="danger" @click="worksDel(item.id)">删除</van-button></div>
          </div>
        </div>
      </div>
    </div>
    <not-find v-if="tabList.length == 0" />
    <div style="height: 0.9rem;"></div>
    <div class="footer-group" v-if="activeStatus == 1">
      <div class="button" @click="shureMethod()" v-if="userRole == 1 && signupStatus == 0">提交作品</div>
      <div class="button" @click="shureMethod1()" v-if="userRole == 2">作品打分</div>
    </div>
    <van-popup v-model="show" closeable position="bottom" :style="{ height: '45%' }">
      <div class="model-title">作品名称</div>
      <van-field required v-model="fileName" label="作品名称" placeholder="作品名称" />
      <div style="margin: 16px;">
        <van-button round block type="info" @click="onSubmitWorks">提交</van-button>
      </div>
    </van-popup>

    <van-popup v-model="show1" closeable position="bottom" :style="{ height: '55%' }">
      <div class="model-title">作品打分</div>
      <van-form>
        <van-field name="uploader" required label="作品上传">
          <template #input>
            <van-radio-group v-model="scoring_num" direction="horizontal">
              <van-radio :name="item" v-for="item in 10" :key="item">{{ item }}分</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field type="textarea" :rows="5" v-model="comment" label="作品评语" placeholder="作品评语" />
      </van-form>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" @click="onSubmitSource">提交</van-button>
      </div>
    </van-popup>
    <wechat :callback="wxReadyOkMethod" pageurl="/weChatApp/renewDetail"/>
    <van-popup v-model="chooseshow" closeable position="bottom" :style="{ height: '25%' }">
      <div class="popup-group">
        <div class="popup-button" @click="chooseshow = false">
          <van-icon size="1rem" name="video-o" />
          <span class="popup-title">视频</span>
          <input class="popup-file" @change="videoFile" type="file" accept="video/*">
        </div>
        <div class="popup-button" @click="chooseImage">
          <van-icon size="1rem" name="photo-o" />
          <span class="popup-title">图片</span>
        </div>
      </div>
    </van-popup>
    <van-popup v-model="videoshow" closeable position="center" :style="{ height: '100vh',width:'100vw' }">
      <div style="height: 0.8rem;"></div>
      <video-play :show="videoshow" ref="videoPlay"
        :play-handler="playHandler"  :video-src="videoSrc"
        :vodie-ready="vodieReady"></video-play>
    </van-popup>
  </div>
</template>
<script>
// import notFind from "@/view/common/notFind";
import videoPlay from '@/view/common/videoPlay';
import { Button, Toast, Popup, Field, Form, Uploader, RadioGroup, Radio, ImagePreview, Icon } from 'vant';
import { findIndex } from 'lodash';
import { getUserRole } from '@/utils/utils';
export default {
  name: "match",
  components: {
    videoPlay, [Button.name]: Button, [Popup.name]: Popup, [Field.name]: Field, [Form.name]: Form,
    [Uploader.name]: Uploader, [RadioGroup.name]: RadioGroup, [Radio.name]: Radio, [Icon.name]: Icon,
    [ImagePreview.Component.name]: ImagePreview.Component
  },
  data() {
    return {
      userRole: getUserRole(),
      show: false,
      show1: false,
      chooseshow: false,
      videoshow: false,
      wxReadyOk: false,
      leftList: [],
      rightList: [],
      tabList: [],
      uploader: [],
      fileName: '',
      imgBasePath: this.$API.ASSET_IMAGES_URL,
      videoBasePath: this.$API.ASSET_VIDEO_URL,
      scoring_num: 1,
      comment: '',
      type: 1,
      memberId: '',
      videoSrc: '',
      signupStatus: 0,
      activeStatus: 0,
      publicPath: process.env.NODE_ENV === 'development'?'/':'/weChatApp/'
    };
  },
  mounted() {
    this.active_id = this.$route.query.activeId;
    this.signup_id = this.$route.query.signupId;
    this.member_id = this.$route.query.memberId;
    this.type = this.$route.query.type;
    this.initAjaxMethod();
  },
  methods: {
    imagePreview(row) {
      if (row.source_type == 1) {
        let imags=this.tabList.filter(o => o.source_type == 1);
        let index = findIndex(imags, o => o.id == row.id);
        ImagePreview({
          images: imags.map(o => this.imgBasePath + o.path),
          closeable: true,
          startPosition: index>=0?index:0
        });
      } else if (row.source_type == 2) {
        this.videoshow=true;
        this.videoSrc=this.videoBasePath+row.path;
      }
    },
    //视频准备
    vodieReady() {
      console.log('视频准备好了');
    },
    //开始播放了
    playHandler() {
      console.log('开始播放了11');
    },
    //列表加载
    initAjaxMethod() {
      Toast.loading({ message: "加载中...", forbidClick: true });
      this.$http
        .post(this.$API.USER_WORKS_LIST, { signup_id: this.signup_id, member_id: this.member_id })
        .then((res) => {
          Toast.clear();
          if (res.code == 1) {
            let list = Array.isArray(res.data) ? res.data : [], leftList = [], rightList = [];
            list.forEach((item, index) => {
              if (index % 2 == 0) {
                rightList.push(item);
              } else {
                leftList.push(item);
              }
            });
            this.leftList = leftList;
            this.rightList = rightList;
            this.tabList = list;
            this.signupStatus = res.signup ? res.signup.status : 0;
            this.activeStatus = res.active ? res.active.status : 1;
          }
        });
    },
    worksDel(id) {
      this.$dialog.confirm({
        title: '提示',
        message: '确定要进行此操作',
      }).then(() => {
        this.worksDelMethod(id);
      }).catch(() => { });
    },
    worksDelMethod(id) {
      Toast.loading({ message: "加载中...", forbidClick: true });
      this.$http
        .post(this.$API.USER_WORKS_DEL, { works_id: id })
        .then((res) => {
          Toast.clear();
          if (res.code == 1) {
            this.$notify({ type: 'success', message: '操作成功' });
            this.initAjaxMethod();
          } else {
            this.$notify({ type: 'warning', message: res.msg });
          }
        });
    },
    shureMethod() {
      if (this.tabList.length == 0) {
        return this.$notify({ type: 'warning', message: '请上传一张作品' });
      }
      this.$dialog.confirm({
        title: '提示',
        message: '请确认，是否要将本次上传作品列表提交报名？',
      }).then(() => {
        this.show = true;
      }).catch(() => { });

    },
    shureMethod1() {
      Toast.loading({ message: "加载中...", forbidClick: true });
      this.$http
        .post(this.$API.IS_PLY_WROKS, {
          signup_id: this.signup_id,
          name: this.fileName
        })
        .then((res) => {
          Toast.clear();
          if (res.code == 1) {
            this.show1 = true;
          } else {
            this.$notify({ type: 'warning', message: res.msg });
          }
        });
    },
    wxReadyOkMethod() {
      console.log('js准备好了');
      this.wxReadyOk = true;
    },
    videoFile(e) {
      let file = e.target.files[0];
      console.log('file', file);
      const formData = new FormData();
      formData.append('file', file);
      Toast.loading({ message: "上传中...", forbidClick: true, duration: 1000000 });
      this.$http
        .post(this.$API.LOGIN_VIDEO, formData, {
          headers: {
            'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarybIUBskeGLlxuOBUg'
          }
        })
        .then((res) => {
          console.log('res', res);
          Toast.clear();
          if (res.code == 1) {
            this.$notify({ type: 'success', message: '上传成功' });
            this.videoRead(res.data, file.name);
          } else {
            this.$notify({ type: 'warning', message: res.msg });
          }
        });
    },
    videoRead(path, name) {
      this.$http
        .post(this.$API.UPLOAD_USER_VIDEO_WORKS, {
          active_id: this.active_id,
          signup_id: this.signup_id,
          path: path,
          name: name
        })
        .then((res) => {
          console.log('res', res);
          Toast.clear();
          if (res.code == 1) {
            this.$notify({ type: 'success', message: '上传成功' });
            this.initAjaxMethod();
          } else {
            this.$notify({ type: 'warning', message: res.msg });
          }
        });
    },
    chooseImage() {
      this.chooseshow = false;
      let that = this;
      this.$WX.checkJsApi({
        jsApiList: ['chooseImage', 'getLocalImgData'],
        success: function (res) {
          console.log('res', res);
          if (res.errMsg == "checkJsApi:ok") {
            that.chooseImages();
          }
        }
      });
    },
    chooseImages() {
      let _this = this;
      this.$WX.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          _this.$WX.getLocalImgData({
            localId: res.localIds[0],
            success: function (ress) {
              let bs64 = ress.localData; // localData是图片的base64数据，可以用 img 标签显示
              if (bs64.indexOf('data:image') != 0) {
                //判断是否有这样的头部，没有就加上
                bs64 = 'data:image/jpeg;base64,' + bs64;
              }
              let content = bs64.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg');
              _this.afterRead(content);
            }
          });
        }
      });
    },
    afterRead(content) {
      Toast.loading({ message: "上传中...", forbidClick: true, duration: 1000000 });
      this.$http
        .post(this.$API.UPLOAD_USER_WORKS, {
          active_id: this.active_id,
          signup_id: this.signup_id,
          base64_image: content
        })
        .then((res) => {
          console.log('res', res);
          Toast.clear();
          if (res.code == 1) {
            this.$notify({ type: 'success', message: '上传成功' });
            this.initAjaxMethod();
          } else {
            this.$notify({ type: 'warning', message: res.msg });
          }
        });
    },
    onSubmitWorks() {
      if (!this.fileName) {
        return this.$notify({ type: 'warning', message: '请输入作品名' });
      }
      Toast.loading({ message: "加载中...", forbidClick: true });
      this.$http
        .post(this.$API.SUBMIT_USER_WORKS, {
          active_id: this.active_id,
          signup_id: this.signup_id,
          name: this.fileName
        })
        .then((res) => {
          Toast.clear();
          if (res.code == 1) {
            this.$notify({ type: 'success', message: '提交成功' });
            this.show = false;
            setTimeout(() => {
              this.$router.back();
            }, 1500);
          } else {
            this.$notify({ type: 'warning', message: res.msg });
          }
        });
    },
    onSubmitSource() {
      Toast.loading({ message: "加载中...", forbidClick: true });
      this.$http
        .post(this.$API.SET_SCORING, {
          active_id: this.active_id,
          signup_id: this.signup_id,
          scoring_num: this.scoring_num,
          comment: this.comment,
        })
        .then((res) => {
          Toast.clear();
          if (res.code == 1) {
            this.$notify({ type: 'success', message: '提交成功' });
            this.$router.back();
          } else {
            this.$notify({ type: 'warning', message: res.msg });
          }
        });
    },
  },
};
</script>
<style lang="less">
.matchSubmit {
  .submit-add {
    padding: 0.1rem;
    display: flex;
    justify-content: flex-end;
  }

  .popup-group {
    padding: 0.7rem 0.2rem 0.2rem 0.2rem;
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 100%;

    .popup-button {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-right: 0.2rem;
      position: relative;
    }

    .popup-title {
      font-size: 0.28rem;
      color: #333;
      padding-top: 0.2rem;
    }

    .popup-file {
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
      height: 100%;
      width: 100%;
    }
  }

  .list-content {
    padding: 0.15rem;
    display: flex;

    .list-group {
      width: 50%;

      .list-box {
        padding: 0.15rem;

        .list-item {
          background-color: #ffffff;
          border-radius: 8px;
          box-shadow: 0px 2px 20px 0px rgba(0, 0, 0, 0.1);
          position: relative;

          img {
            width: 100%;
            height: auto;
            display: block;
          }

          .title {
            padding: 0.2rem 0.1rem;
            font-size: 0.3rem;
            color: #333;
            word-break: break-all;
          }

          .del {
            padding: 0.2rem 0.1rem;
          }
        }
      }
    }
  }

  .footer-group {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 0.1rem 0.3rem;
    padding: 0.1rem;

    .button {
      height: 0.9rem;
      line-height: 0.9rem;
      text-align: center;
      font-size: 0.3rem;
      color: #fff;
      border-radius: 0.9rem;
      background: #409eff;
    }
  }

  .model-title {
    padding: 0.3rem;
    font-size: 0.3rem;
    text-align: center;
    color: #333;
  }

  /* 插件部分样式重置 */
  .van-cell {
    padding: 0.3rem 0.3rem;
    font-size: 0.3rem;
    line-height: 0.48rem;
  }

  .van-cell__title {
    font-size: 0.3rem;
  }

  .van-uploader__input,
  .van-uploader__input-wrapper {
    font-size: 0;
  }

  .van-radio {
    padding: 0.08rem;

    .van-radio__label {
      font-size: 0.3rem;
    }
  }
}
</style>